package com.enotourister.core.pool;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.enotourister.core.proposal.Proposal;
import com.enotourister.core.proposal.ProposalListener;
import com.enotourister.core.rfp.RequestForProposal;

public class Pool implements java.io.Serializable {
	private static final long serialVersionUID = 7504194213388012218L;
	private static Pool INSTANCE = new Pool();
	private Map<RequestForProposal, List<Proposal>> pool = null;
	private List<ProposalListener> listeners = null; 
	
	private Pool() {
		pool = new Hashtable<RequestForProposal, List<Proposal>>();
		listeners = new ArrayList<ProposalListener>();
	}
	
	public static Pool getInstance() {
		return INSTANCE;
	}
	
	public void addProposal(Proposal proposal) {
		List<Proposal> proposals = null;
		
		if (!pool.containsKey(proposal.getRequestForProposal())) {
			proposals = new Vector<Proposal>();
			proposals.add(proposal);
			
			pool.put(proposal.getRequestForProposal(), proposals);
		} else { 
			proposals = pool.get(proposal.getRequestForProposal());
			proposals.add(proposal);
		}	
		
		// Calling listeners
		sendProposalToSubscribers(proposal);
	}
	
	private void sendProposalToSubscribers(Proposal proposal) {
		RequestForProposal rfp = proposal.getRequestForProposal();

		for (ProposalListener listener : listeners) {
			if (rfp.equals(listener.getRequestForProposal())) 
				listener.submitProposal(proposal);
		}
	}
	
	public List<Proposal> getProposals(RequestForProposal rfp) {
		return pool.get(rfp);
	}
	
	public void subscribe(ProposalListener proposalListener) {
		listeners.add(proposalListener);
	}

	public void unsubscribe(ProposalListener proposalListener) {
		listeners.remove(proposalListener);
	}

}
